﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Microsoft.Phone.Controls;

namespace WP7SignalRHelperClient
{
    public partial class GameScores : PhoneApplicationPage
    {
        #region "Constructor"

        public GameScores()
        {
            InitializeComponent();           
        }

        #endregion

        #region "Event Handlers"

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // Instantiate with default or any other implementation.
            App.Current.SignalRHub = new SignalRMessagingHub();

            // Wire-up to listen to custom event from SignalR Hub.
            App.Current.SignalRHub.SignalRServerNotification += new SignalRServerHandler(SignalRHub_SignalRServerNotification);

            GameScoreClient phoneToFollowGame = new GameScoreClient();
            phoneToFollowGame.PhoneClientId = App.Current.DeviceID;

            // Send to server to follow a Live Game.
            App.Current.SignalRHub.FollowLiveGame(phoneToFollowGame);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            // Unwire.
            App.Current.SignalRHub.SignalRServerNotification -= new SignalRServerHandler(SignalRHub_SignalRServerNotification);
        }

        protected void SignalRHub_SignalRServerNotification(object sender, SignalREventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                // Update scores on phone.
                teamAScore.Text = e.TeamAScore.ToString();
                teamBScore.Text = e.TeamBScore.ToString();
            }));
        }

        #endregion
    }
}